<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
</head>
<body>
	<h1>canvas图片处理</h1>
	<div>选择本地图片:
		<input type="file" id="file" name="file" onchange="setFile()" placeholder="请选择一张本地图片">
	</div>
	<div>
	<button onclick="filterGrey()">灰度处理</button>
	<button onclick="filterReverse()">反色</button>
	<br/>	
	<span id="colorResult"></span>	
	<input type="button" name="toWhite" onclick="filterDiff(255,255,255)" value="差变为白色（255，255，255）">
	<button onclick="filterTo(255,255,255)">替换为白色（255，255，255）</button>
	<br/>
	<button onclick="blurAvg = true">平均色处理</button>
	</div>
	<!--
	<div>
		<form>马赛克：
			<input type="number" name="width" placeholder="宽（px)" min="1" step="1">x<input type="number" name="height" placeholder="高（px)" min="1" step="1">
			<input type="radio" name="type" value="1" checked>长方形
			<input type="radio" name="type" value="0">（椭）圆形
			<button onclick="">确定并选择位置</button>
		</form>
	</div>
	-->
	<canvas id="canvas">
		你的浏览器不支持canvas
	</canvas>

	<script type="text/javascript">
		var canvas = document.getElementById("canvas")
		var ctx = canvas.getContext("2d")

		var image = new Image()

		let setFile = function (e,areaId){
			e = e || window.event;
			if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
		        alert("很遗憾，您浏览器版本太老了，无法使用我们的小工具 ！");
		        return;
		    }
		    //console.log(e);
			//if(e.files.length > 0)$(areaId).src = getObjectURL(e.files[0]);
			var files=document.getElementById("file").files;
			//document.getElementById("pic").innerHTML="";
			if(files.length>0){
				var fr=new FileReader();
				fr.readAsDataURL(files[0]);
				fr.onload=function(c){
					image.src = c.target.result;
				};

			}			
		}
		image.onload = function(){
			canvas.width = image.width;
			canvas.height = image.height;
			ctx.drawImage(image,0,0);
		}
		function windowToCanvas(x,y){
			var bbox = canvas.getBoundingClientRect()
			return {x:x-bbox.left,y:y-bbox.top}
		}
		var rgba = null;
		var point0 = null;
		var point1 = null;
		canvas.onmousedown = function(e){
			e.preventDefault()

			var point = windowToCanvas(e.clientX,e.clientY);
			//console.log(e.clientX,e.clientY)
			console.log(point.x,point.y)

			//获取(x,y,1,1)的像素数据对象
			let imgData = ctx.getImageData(point.x,point.y, 1, 1);
			console.log(imgData.data);
			//background-color使用
			let color16 = '#'+ hexadecimal(imgData.data[0]) + hexadecimal(imgData.data[1]) + hexadecimal(imgData.data[2]);
			str = '<span style="background-color:'+ color16 +'">&nbsp;&nbsp;&nbsp;&nbsp;</span>'+ color16;		
			str1 = '&nbsp;&nbsp;RGB:'+ imgData.data.slice(0,3);
			//在html中显示颜色和对应的颜色码
			document.getElementById("colorResult").innerHTML = str+str1;		
			rgba = imgData.data;
			point0 = point;
		}
		//十六进制转换器
		let hexadecimal = function(num) {
		    var r = parseInt(num).toString(16);
		    if (r.length == 1) {
		        return '0' + r;
		    }
		    return r.toUpperCase();
		}
		function filterDiff(r,g,b,a){
			if(rgba == null){
				alert("请先点击图片选择颜色 ！");
		        return;
			}
			var imageData = ctx.getImageData(0,0,canvas.width,canvas.height);
			var pixelData = imageData.data;
			var diff = [r-rgba[0],g-rgba[1],b-rgba[2]];
			//console.log(diff);
			for (var i = 0;i<canvas.width * canvas.height;i++){
				var r = pixelData[i*4+0]+diff[0];
				var g = pixelData[i*4+1]+diff[1];
				var b = pixelData[i*4+2]+diff[2];

				pixelData[i*4+0] = r>255?r-255:r;
				pixelData[i*4+1] = g>255?g-255:g;
				pixelData[i*4+2] = b>255?b-255:b;

			}
			ctx.putImageData(imageData,0,0);
		}
		function filterTo(pr,pg,pb,pa){
			if(rgba == null){
				alert("请先点击图片选择颜色 ！");
		        return;
			}
			var imageData = ctx.getImageData(0,0,canvas.width,canvas.height);
			var pixelData = imageData.data;
			for (var i = 0;i<canvas.width * canvas.height;i++){
				var r = pixelData[i*4+0];
				var g = pixelData[i*4+1];
				var b = pixelData[i*4+2];

				pixelData[i*4+0] = r==rgba[0]?pr:r;
				pixelData[i*4+1] = g==rgba[1]?pg:g;
				pixelData[i*4+2] = b==rgba[2]?pb:b;

			}
			ctx.putImageData(imageData,0,0);
		}
		function filterReverse(){
			var imageData = ctx.getImageData(0,0,canvas.width,canvas.height);
			var pixelData = imageData.data;
			for (var i = 0;i<canvas.width * canvas.height;i++){
				var r = pixelData[i*4+0];
				var g = pixelData[i*4+1];
				var b = pixelData[i*4+2];

				pixelData[i*4+0] = 255 - r;
				pixelData[i*4+1] = 255 - g;
				pixelData[i*4+2] = 255 - b;
			}
			ctx.putImageData(imageData,0,0);
		}
		function filterGrey(){
			var imageData = ctx.getImageData(0,0,canvas.width,canvas.height);
			var pixelData = imageData.data;
			for (var i = 0;i<canvas.width * canvas.height;i++){
				var r = pixelData[i*4+0];
				var g = pixelData[i*4+1];
				var b = pixelData[i*4+2];

				var grey = r*0.3 + g*0.59+b*0.11

				pixelData[i*4+0] = grey;
				pixelData[i*4+1] = grey;
				pixelData[i*4+2] = grey;
			}
			ctx.putImageData(imageData,0,0);
		}
		var blurAvg = false;
		function filterAvg(){
    		//bluring = true;
			//var blurR = 9;
			var tmpWidth = Math.abs(point1.x-point0.x);
			var tmpHeith = Math.abs(point1.y-point0.y);
			var totalPx = tmpWidth * tmpHeith;
			console.log(tmpWidth,tmpHeith);

			var tmpImageData = ctx.getImageData(point0.x,point0.y,tmpWidth,tmpHeith);
			var tmpPixelData = tmpImageData.data;
			var totalr = 0,totalg = 0,totalb = 0;
			for (var i = 0;i<totalPx;i++){
				totalr += tmpPixelData[i*4+0];
				totalg += tmpPixelData[i*4+1];
				totalb += tmpPixelData[i*4+2];
			}
			for (var i = 0;i<totalPx;i++){
				tmpPixelData[i*4+0] = totalr/totalPx;
				tmpPixelData[i*4+1] = totalg/totalPx;
				tmpPixelData[i*4+2] = totalb/totalPx;
			}				
			ctx.putImageData(tmpImageData,point0.x,point0.y);    		
		}
		canvas.onmouseup = function(e){
			e.preventDefault();
			//console.log("onmouseup");
			var pointThis = windowToCanvas(e.clientX,e.clientY);
			console.log(pointThis);	
			point1 = pointThis;
			//ctx.strokeRect(point0.x, point0.y, Math.abs(point1.x-point0.x), Math.abs(point1.y-point0.y));
			if(blurAvg == true){
				filterAvg();
			}
		}				
	</script>
</body>
</html>